package com.ms.education.statistics.schedule;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.ms.education.statistics.service.StatisticsDailyService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project:education-ScheduleDaily
 * <p>Powered by ms on 2023-01-22 15:47:12
 *
 * @author ms
 * @version 1.0
 * @since 1.8
 */
//@Component
public class ScheduleDaily {

    @Autowired
    private StatisticsDailyService statisticsDailyService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private static final String SCHEDULE_STATISTIC_DAILY="schedule:statistic:daily";

    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0/6 * * * * ?")
    public void countDaily() {
        //进入定时任务首先添加一个后置任务
        /*
        给定时任务一个时间上限45秒
        45秒之后如果没有显示成功，这里没有显示成功代表其他主机执行失败，本主机接管任务
         */
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                Long nums = redisTemplate.countExistingKeys(Arrays.asList("success", SCHEDULE_STATISTIC_DAILY));
                if (nums==0){
                    countDaily();
                }
            }
        }, 45000);

        RLock lock = redissonClient.getLock(SCHEDULE_STATISTIC_DAILY);
        lock.lock();
        try {
            String date=DateUtil.yesterday().toString("yyyy-MM-dd");
            statisticsDailyService.createDailyDate(date);
            /*
            如果任务执行成功,王redis中添加任务执行成功标记
             */
            redisTemplate.opsForValue().set("success",SCHEDULE_STATISTIC_DAILY,1,TimeUnit.MINUTES);
        }finally {
            lock.unlock();
        }
    }

}
